<template>
  <div class="myContent">
    <!-- 1. 顶部 -->
    <div class="top">
      <h1>我的内容</h1>
      <el-button @click="router.push('/')">返回</el-button>
    </div>

    <!-- 2.我的列表 -->
    <div class="tableBox">
      <!-- <el-scrollbar height="100%"> -->
      <div class="myContentList" v-if="true">
        <!--音频  -->
        <!-- <audio id="media" src="http://www.abc.com/test.mp3" controls></audio>   -->

        <!-- 视频 -->
        <!-- <video id="media" src="https://www.51miz.com/shipin/ae/178329.html?keyword_id=92428" controls width=”400px” heigt=”400px”></video>   -->
        <!-- 3.2 设备列表-->
        <el-table
          :row-key="getRowKeys"
          :data="tableData"
          style="width: 100%"
          :header-cell-style="{ background: '#F5F9FC' }"
          @selection-change="selectionChange"
          ref="tableRef"
          v-loading="isLoading"
          @row-click="goTodetailPage"
        >
          <el-table-column
            type="selection"
            prop="sec"
            label=""
            min-width="60"
            :reserve-selection="false"
          />
          <el-table-column prop="fileName" label="文件" min-width="509">
            <template #default="scope">
              <div class="fileContainer">
                <div class="fileImg" >
                  <img v-if="scope.row.picture" :src="scope.row.picture" class="img" />
                  
                  <!-- 视频：flv不行，avi，mov可以，m4v可以，mwv -->
                  <img
                    v-if="!scope.row.picture && ((scope.row.fileName.indexOf('.mp4') > -1) ||(scope.row.fileName.indexOf('.m4v') > -1) ||(scope.row.fileName.indexOf('.flv') > -1)||(scope.row.fileName.indexOf('.avi') > -1)||(scope.row.fileName.indexOf('.mov') > -1)||(scope.row.fileName.indexOf('.wmv') > -1))"
                    src="@/assets/my_content/video.png"
                    class="defaultImg2"
                  />
                  <!-- 音频： m4a、wav、pcm、amr -->
                  <img
                    v-if="!scope.row.picture &&(scope.row.fileName.indexOf('.mp3') > -1 || scope.row.fileName.indexOf('.m4a') > -1 || scope.row.fileName.indexOf('.wav') > -1 || scope.row.fileName.indexOf('.pcm') > -1 || scope.row.fileName.indexOf('.amr') > -1)"
                    src="@/assets/my_content/audio.png"
                    class="defaultImg2"
                  />
                </div>
                <div class="fileInfo">
                  <div v-if="scope.row.isShowInput">
                    <!-- @keyup.enter="blur(scope.row)" -->
                    <el-input
                      v-model="renameValue"
                     
                      @blur="blur(scope.row)"
                      placeholder="请输入标题"
                      clearable
                      maxlength="50"
                      ref="inputRef"
                      @keyup.enter.prevent="handleEnter(scope.row)"
                    />
                  </div>
                  <div v-else>{{ scope.row.title }}</div>
                  
                  <!-- 失败 -->
                  <div v-if="scope.row.transferFail==1">
                    
                    <img src="@/assets/home/error.png" />
                    <span v-if="!scope.row.errorMsg" style="color: rgba(245, 34, 45, 1)">失败</span>
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      :content="scope.row.errorMsg"
                      placement="right-start"
                      v-else
                    >
                      <span style="color: rgba(245, 34, 45, 1)">失败</span>
                    </el-tooltip>
                  </div>
                  <!-- scope.row.transferFail==0  成功 / 待定-->
                  <template v-else>
                    <div v-if="scope.row.transferRate >= 100">
                      <span>{{scope.row.totalTime? gettotalTimeHMS(scope.row.totalTime): scope.row.totalTime }}</span>
                    </div>
                    <div v-else>
                      <img src="@/assets/home/4.png" />
                      <span style="color: rgba(255, 169, 64, 1);">转写中...{{ scope.row.transferRate }}%</span>
                    </div>
                  </template>
                  
                </div>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="userName" label="不限归属" min-width="109" /> -->
          <el-table-column prop="createdTime" label="创建时间" min-width="209" >
           <template #default="scope">
               {{getYMDHS(scope.row.createdTime)}} 
             </template>
          </el-table-column>
          <el-table-column prop="opration" label="操作" min-width="120" fixed="right">
            <!-- scope.row   -->
            <template #default="scope">
              <el-button link type="primary" size="small" @click.prevent.stop="edititem(scope.row)">
                重命名
              </el-button>
              <el-button link type="primary" size="small" @click.prevent.stop="deleteitem(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- </el-scrollbar> -->
    </div>

    <!-- 3. 分页 -->
    <div class="pagination-block">
      <!-- 批量删除按钮 -->
      <el-button
        :class="['shiftBtn', selectRows.length > 0 ? 'active' : '']"
        @click="shiftBtns"
        type="danger"
        >删除</el-button
      >
      <div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="sizes,prev,  pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <div>页</div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { useRouter } from 'vue-router'
import {ref, onMounted ,onBeforeUnmount,nextTick} from 'vue'

import { ElMessage, ElMessageBox } from 'element-plus'
const router = useRouter()
// import axios from 'axios'

import { request } from '@/utils/server.js'

// 获取组织信息，并传递给后端
// const userId = ref(sessionStorage.getItem('userId') || '4233dfdf4')
const userId = ref(sessionStorage.getItem('userId') || '4600072255')

console.log(userId.value)

// 1.----获取我的内容列表接口-----
const isLoading = ref(false)
const getMyContentList = () => {
  isLoading.value = true
  request
    .get(
      '/sweet-api/mypage/' +
        userId.value +
        '?current=' +
        currentPage.value +
        '&pageSize=' +
        pageSize.value
    )
    .then((res) => {
      // debugger
      // console.log("我的内容列表获取成功",res.data);
      if (res.data.code == 1) {
        let list = res.data.data || []
        list.forEach((item) => {
          item.isShowInput = false
        })
        tableData.value = list

        // 总条数
        total.value = res.data.total
      }
    })
    .catch((error) => {
      console.log('我的内容列表获取失败', error)
    })
    .finally(() => {
      isLoading.value = false
    })
}

//  2.----删除我的内容接口-----
const tableRef = ref('')
const delateRecentlyItem = (ids) => {
  request
    .post('/sweet-api/mypage/delete?ids=' + ids.join(','))
    .then((res) => {
      // debugger
      // console.log("最近列表获取成功",res.data);
      getMyContentList()

      selectRows.value = []
      // 清除勾选
      tableRef.value.clearSelection()
    })
    .catch((error) => {
      console.log('最近列表获取失败', error)
    })
}
//3.----重命名接口----
const resetName = (row, value) => {
  // debugger
  request
    .post('/sweet-api/file/rename', {
      id: row.id,
      name: value
    })
    .then((res) => {
      //  debugger
      // console.log("重命名成功",res.data);
      if (res.data.code == 1) {
        // 隐藏输入框
        row.isShowInput = false
        ElMessage({
          message: '重命名成功',
          type: 'success'
        })

        //重命名成功，重新调用展示列表
        getMyContentList()
      } else {
        ElMessage({
          message: res.data.msg || '重命名失败',
          type: 'error'
        })
      }
    })
    .catch((error) => {
      console.log('重命名失败', error)
      ElMessage({
        message: error || '重命名失败',
        type: 'error'
      })
    })
}

onMounted(() => {
  getMyContentList()

  // 轮询刷新
  setTimeoutZdy(option)
})

// 生命周期:销毁前
onBeforeUnmount(() => {
  // 退出页面 停止轮询
  option.isClose = true
})

// 1.搜索
const inputValue = ref('')

// 2. 最近列表
const tableData = ref([
  // {
  //   createdTime: '2023年7月1日 下午3:08', //创建时间
  //   currentStatus: 0,
  //   deleteTime: '',
  //   exitOss: 0, //视频上传状态
  //   fileName: '', //视频名字
  //   flag: 0,
  //   id: 0, //视频id
  //   inputId: '',
  //   isShow: 0,
  //   ownby: '',
  //   picture: '',
  //   recentUsedTime: '', //最近使用时间
  //   title: '',
  //   totalTime: '',
  //   transferVideo: 0, //语义语义转换是否完成
  //   url: '', //视频播放连接
  //   userId: '',
  //   userName: '张小瑞' //用户姓名
  // }
])
const getRowKeys = (row) => {
  return row.id
}

// 轮询刷新--更新转写状态
const setTimeoutZdy = (option) => {
  setTimeout(function () {
    // console.log("轮询")
    // debugger
    try {
      if (typeof option.fn == 'function') {
        option.fn()
        if (option.isClose) {
          return
        }
      }
    } catch {}
    setTimeoutZdy(option)
  }, option.time || 5000)
}
var option = {
  isClose: false,
  fn: () => {
    let total=0
      for(let i=0;i<tableData.value.length;i++){
        let item=tableData.value[i]
        if(item.transferFail==0 && item.transferRate<100){
          total++   
        }
      }
    if(total==0){
      option.isClose=false
    }else{
      request
      .get(
        '/sweet-api/mypage/' +
          userId.value +
          '?current=' +
          currentPage.value +
          '&pageSize=' +
          pageSize.value
      )
      .then((res) => {
        // debugger
        // console.log("最近列表获取成功",res.data);
        if (res.data.code == 1) {
          // debugger
          for (let i = 0; i < tableData.value.length; i++) {
              for (let j = 0; j < res.data.data.length; j++) {
                if (tableData.value[i].id == res.data.data[j].id) {
                  // console.log(i,j)
                  tableData.value[i].transferFail = res.data.data[j].transferFail
                  tableData.value[i].transferRate = res.data.data[j].transferRate
                  tableData.value[i].picture = res.data.data[j].picture
                  tableData.value[i].totalTime = res.data.data[j].totalTime
                  tableData.value[i].errorMsg = res.data.data[j].errorMsg || ''
                }
              }
          }
        }
      })
      .catch((error) => {
        console.log('最近列表获取失败', error)
      })
      
    }
      
  },
  time: 5000
}

//获取年月日时分
const getYMDHS=(dateStr)=>{
  let date = new Date(dateStr);

  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hours = date.getHours();
  
  let minutes = date.getMinutes();
  minutes=(minutes<=9)?('0'+minutes):minutes;
  let seconds = date.getSeconds();

  let period = hours < 12 ? "上午" : "下午";
  let displayHours = hours > 12 ? hours - 12 : hours;

  let formattedDate = `${year}年${month}月${day}日 ${period}${displayHours}:${minutes}`;

  // console.log(formattedDate);
  return formattedDate
}

//如果2位数字的第一位为0，则去除0
const del0=(arr)=>{
  let str=arr.toString()
  if(str[0]==0){
    str=str.slice(1)
  }
  return str
}
// 获取文件时长：时分秒
const gettotalTimeHMS=(totalTime)=>{
  let arr= totalTime.split(":") || totalTime.split("：")
  let time
  if(arr.length==2){
    time=del0(arr[0]) +'分'+del0(arr[1])+'秒'
    
    return time
  }else if(arr.length==3){
    time=del0(arr[0]) +'时'+del0(arr[1]) +'分'+del0(arr[2])+'秒'

    return time
  }else{
    return totalTime
  }
}
// 点击图片，跳转到音视频详情页row.transferRate == 100 && row.transferFail == 0 &&
const goTodetailPage = (row) => {
  if ( row.totalTime && !row.isShowInput && row.transferRate == 100 &&row.transferFail == 0  ) {
    if (row.fileName && (row.fileName.slice(-3) == 'mp4' || row.fileName.slice(-3) == 'm4v' || row.fileName.slice(-3) == 'flv'|| row.fileName.slice(-3) == 'avi'|| row.fileName.slice(-3) == 'mov'|| row.fileName.slice(-3) == 'wmv')) {
      router.push({
        path: '/video-page',
        query: {
          userId:userId.value,
          id: row.id,
          // title: row.title,
          // createdTime: row.createdTime,
          // totalTime: row.totalTime,
          // userName: row.userName,
          url: row.url,
          inputValue: inputValue.value ? inputValue.value : '',
         
          from:'mycontent',

        }
      })
    } else if(row.fileName && (row.fileName.slice(-3) == 'mp3' ||row.fileName.slice(-3) == 'm4a'||row.fileName.slice(-3) == 'wav')){
      router.push({
        path: '/audio-page',
        query: {
          userId:userId.value,
          id: row.id,
          // title: row.title,
          // createdTime: row.createdTime,
          // totalTime: row.totalTime,
          // userName: row.userName,
          url: row.url,
          inputValue: inputValue.value ? inputValue.value : '',
         
          from:'mycontent'
        }
      })
    }
  }
}

// 3.重命名
// 输入框内容
const renameValue = ref('')
console.log(renameValue.value)
const inputRef = ref('')

const edititem = (row) => {
  row.isShowInput = true
  renameValue.value = row.title
  nextTick(() => {
    // debugger
    inputRef.value.focus()
  })
}

// 输入框失去焦点
const blur = (row) => {
  // debugger
  if(renameValue.value){
    // 隐藏输入框
    row.isShowInput = false

    nextTick(()=>{
      //调用重命名接口
      resetName(row, renameValue.value)
    })
  }
}
const handleEnter=(row)=>{
  //  debugger
   console.log(111)
   // 隐藏输入框
  row.isShowInput = false
}


// 单个删除
const deleteitem = (row) => {
  // debugger
  console.log(row.url)

  ElMessageBox.confirm('确定删除当前选中项吗？', '删除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      //单个删除请求（成功后发查询请求）
      delateRecentlyItem([row.id])
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

// 跨页勾选, 删除时选中行
const selectRows = ref([])
const selectionChange = (selection) => {
  selectRows.value = selection
  // console.log('选中', selectRows.value)
}

// 批量删除
const shiftBtns = () => {
  // console.log('selectRows.value', selectRows.value)
  let ids = []
  selectRows.value.forEach((item) => {
    ids.push(item.id)
  })
  ElMessageBox.confirm('确定删除当前选中项吗？', '删除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      // 发请求  批量删除接口
      delateRecentlyItem(ids)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

// 3.分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  //重新发请求，渲染设备列表
  getMyContentList()
}
const handleCurrentChange = (val) => {
  // console.log(`current page: ${val}`)
  //重新发请求，渲染设备列表
  getMyContentList()
}
</script>

<style lang="less" scoped>
.myContent {
  margin: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;

  // 2. 头部
  .top {
    width: 100%;
    height: 67px;
    border-bottom: 1px solid rgba(239, 239, 239, 1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: none;

    h1 {
      height: 35px;
      color: rgba(51, 51, 51, 1);
      font-size: 24px;
      text-align: left;
      font-family: SourceHanSansSC-medium;
    }

    .el-button {
      width: 90px;
      height: 32px;
      border-radius: 2px;
      color: rgba(51, 51, 51, 1);
      font-size: 14px;
      text-align: center;
      font-family: Roboto;
      border: 1px solid rgba(206, 206, 206, 1);
    }
  }

  // 2. 会议列表
  .tableBox {
    flex: 1;
    overflow: hidden;
    .myContentList {
      width: 100%;
      height: 100%;
      padding-top: 14px;
      display: flex;
      flex-wrap: wrap;

      :deep(.el-table) {
        height: 100%;
        .fileContainer {
          display: flex;
          justify-content: flex-start;

          .fileImg {
            width: 160px;
            height: 90px;
            background-color: lightgray;
            border-radius: 4px;
            position: relative;
            margin-right: 20px;
            img {
              width: 160px;
              height: 100%;
            }
          
          }
          .fileInfo {
            // width: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;

            & > div {
              display: flex;

              img {
                width: 18px;
                height: 18px;
                margin-right: 4px;
                margin-top: 3px;
              }
            }
            &>div:nth-child(1){
              overflow: hidden;
              text-overflow: ellipsis;
              width: 100%;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
              word-break: break-all;

              color: rgba(51, 51, 51, 1);
              font-size: 16px;
              text-align: left;
              font-family: SourceHanSansSC-regular;
            }
          }
        }
        //移除按钮
        .cell .el-button:nth-child(2) > span {
          color: red;
        }
        .el-table__header-wrapper thead .cell {
          color: rgba(51, 51, 51, 1);
          border-left: 1px solid rgba(206, 206, 206, 1);
        }
        .el-table__header-wrapper thead th:nth-child(1) .cell {
            border-left: none;
        }
      }
    }
  }

  // 3.分页
  .pagination-block {
    width: 100%;
    height: 52px;
    line-height: 52px;
    // border: 1px solid red;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: none;
    // 分页
    & > div {
      display: flex;
      justify-content: flex-end;
      .el-button {
        width: 48px;
        height: 32px;
        line-height: 32px;
        margin: 10px 10px 10px 8px;
        border-radius: 3px;
        background-color: rgba(79, 168, 249, 1);
        color: rgba(255, 255, 255, 1);
        font-size: 14px;
        text-align: center;
        font-family: Roboto;
      }
    }

    // 删除按钮
    .shiftBtn {
      width: 80px;
      height: 32px;
      line-height: 32px;
      border-radius: 2px;
      // background-color: rgba(255, 77, 79, 1);
      color: rgba(255, 255, 255, 1);
      font-size: 14px;
      text-align: center;
      font-family: Roboto;
      opacity: 0;
    }
    .active {
      opacity: 1;
    }
  }

  .upload-demo {
    position: relative;
    z-index: 200;
    top: 0px;
  }
}
</style>
